﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Serialization;

namespace ttg_internal.Utilities.UsageVisualizer.Other
{
    /// <summary>
    /// Storage class for <see cref="IconMap" />
    /// </summary>
    public class IconMapStorage
    {
        public string[][] DeviceMap;
        public string[][] SubsystemMap;
    }

    /// <summary>
    /// Map of device icons container
    /// </summary>
    internal sealed class IconMap
    {
        /// <summary>
        /// Initializes a new instance
        /// </summary>
        private IconMap()
        {
            //
        }

        // Singleton
        private static IconMap _instance;

        /// <summary>
        /// Single instance
        /// </summary>
        public static IconMap Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new IconMap();
                }

                return _instance;
            }
        }

        // Private fields
        private Dictionary<string, string> _deviceMap;
        private string[][] _subsystemMap;

        /// <summary>
        /// Map of device icons
        /// </summary>
        public Dictionary<string, string> DeviceMap
        {
            get
            {
                if (_deviceMap == null)
                {
                    LoadMap();
                }

                return _deviceMap;
            }
            private set { _deviceMap = value; }
        }

        public string[][] SubsystemMap
        {
            get
            {
                if (_subsystemMap == null)
                {
                    LoadMap();
                }

                return _subsystemMap;
            }
            private set { _subsystemMap = value; }
        }

        private void LoadMap()
        {
            string mapFileName = Path.Combine(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Devices"), "IconMap.xml");
            var xmlSerializer = new XmlSerializer(typeof(IconMapStorage));

            using (FileStream fileStream = File.OpenRead(mapFileName))
            {
                var iconMapStorage = (IconMapStorage)xmlSerializer.Deserialize(fileStream);

                for (int i = 0; i < iconMapStorage.DeviceMap.Length; ++i)
                {
                    iconMapStorage.SubsystemMap[i][0] = iconMapStorage.SubsystemMap[i][0].ToLower();
                }

                DeviceMap = iconMapStorage.DeviceMap.ToDictionary(arr => arr[0].ToLower(), arr => arr[1]);
                SubsystemMap = iconMapStorage.SubsystemMap;
            }
        }
    }
}
